import { pageNeeds } from '@/services/api/api-needs';
import { parse } from '@/utils/historyUtils';
import { ProColumns } from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Input, Space, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DetailsNeeds from './DetailNeeds';

interface TableApprovalNeedsProps {
  refresh: string;
  onRefurbish: () => void;
}

const TableApprovalNeeds: React.FC<TableApprovalNeedsProps> = ({ refresh, onRefurbish }) => {
  const access = useAccess();

  const [width, setWidth] = useState(500);
  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);
  const actionRef = useRef<ActionType>();

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  const [id, setIdState] = useState<string>();

  useEffect(() => {
    const { id } = parse(location.search) as { id: string };

    console.log('==useEffect===', id);

    setIdState(id);
  }, []);

  useEffect(() => {
    if(actionRef) {
      actionRef.current?.reloadAndRest();
    }
  }, [refresh]);

  const columns: ProColumns<NeedsData.NeedsPage>[] = [
    {
      title: '状态',
      dataIndex: 'name',
      width: '100px',
      search: false,
      ellipsis: true,
      align: 'center',
      render: (dom, record, _index, action) => {
        return (
          <>
            {record.isApproval === 1 ? (
              <Tag
                style={{
                  margin: 0,
                }}
                color="green"
              >
                已发布
              </Tag>
            ) : (
              <Tag
                style={{
                  margin: 0,
                }}
                color="blue"
              >
                审批中
              </Tag>
            )}
          </>
        );
      },
    },
    {
      title: '进度',
      dataIndex: 'name',
      search: false,
      ellipsis: true,
      hidden: access.媒体采访x配置x发布者,
      align: 'center',
      render: (dom, record, _index, action) => {
        return (
          <>
            {access.媒体采访x配置x管理员 && (
              <Space>
                {record.isHasWaitAsk === 0 ? (
                  <Tag color="green">无等待批示</Tag>
                ) : (
                  <Tag color="orange">有等待批示</Tag>
                )}
              </Space>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'name',
      width: '100px',
      search: false,
      ellipsis: true,
      hidden: access.媒体采访x配置x发布者,
      align: 'center',
      render: (dom, record, _index, action) => {
        return record.isHasAsk === 1 ? <Tag color="green">有请示</Tag> : <>-</>;
      },
    },
    {
      title: '采访主题',
      dataIndex: 'name',
      width: '250px',
      search: false,
      ellipsis: true,
      align: 'center',
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            <DetailsNeeds
              submitId={id}
              id={record.id}
              name={record.name}
              onRefurbish={() => {
                actionRef?.current?.reload();
              }}
            />
          </div>
        );
      },
    },
    {
      title: '发起单位',
      key: 'createdOrganizationAvatar',
      dataIndex: 'createdOrganizationAvatar',
      align: 'center',
      search: false,
      width: '180px',
      valueType: 'avatar',
      render: (dom, row) => (
        <div
          style={{
            textAlign: 'left',
            marginLeft: '24px',
          }}
        >
          <span>{dom}</span>
          {row.createdOrganizationName}
        </div>
      ),
    },

    {
      title: '采访媒体',
      dataIndex: 'assignOrganizationNames',
      hideInSearch: true,
      width: '200px',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      render: (dom, record, _index, action) => {
        let mediaNames = record?.assignOrganizationNames;

        if (mediaNames.length > 2) {
          mediaNames = mediaNames.slice(0, 2);
          mediaNames.push('...');
        }
        return (
          <Space wrap size="small">
            {mediaNames.map((item) => {
              return <Tag key={item}> {item}</Tag>;
            })}
          </Space>
        );
      },
    },
    {
      title: '采访时间',
      dataIndex: 'interviewees',
      key: 'interviewees',
      width: '180px',
      align: 'center',
      valueType: 'dateRange',
      search: false,
      render: (dom, record, _index, action) => {
        return (
          <span>
            {dayjs(record.interviewTimes[0]).format('YYYY-MM-DD')} -
            {dayjs(record.interviewTimes[1]).format('YYYY-MM-DD')}
          </span>
        );
      },
    },
  ];

  return (
    <ProTable<NeedsData.NeedsPage>
      columns={columns}
      actionRef={actionRef}
      request={async (params = {}) => {
        const response = await pageNeeds({
          ...queryParam,
          ...params,
          isRelease: 0,
        });

        return Promise.resolve({
          data: response.data.data,
          total: response.data.total,
          success: response.code === 0,
        });
      }}
      rowKey="id"
      dateFormatter="string"
      bordered
      search={false}
      sticky
      ghost
      scroll={{
        x: '1300px',
      }}
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      headerTitle={
        <div
          style={{
            display: 'flex',
          }}
        >
          <Input.Search
            placeholder="查询标题"
            enterButton="搜索"
            allowClear
            style={{ maxWidth: 250, width: '100%' }}
            onChange={(e) => {
              setQueryParamState({ ...queryParam, name: e.target.value, content: e.target.value });
            }}
            onSearch={(value) => {
              actionRef.current?.reset();
            }}
          />
        </div>
      }
    />
  );
};
export default TableApprovalNeeds;
